package com.youxue.pdf;

import java.util.Calendar;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.lidong.pdf.PDFView;
import com.lidong.pdf.R;
import com.lidong.pdf.listener.OnDrawListener;
import com.lidong.pdf.listener.OnLoadCompleteListener;
import com.lidong.pdf.listener.OnPageChangeListener;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

public class PdfActivity extends Activity implements OnPageChangeListener
    , OnLoadCompleteListener, OnDrawListener {
    private String mPdfUrl;
    private String mPdfTitle;
    private PDFView mPdfView;
    private TextView mOpenFail;
    private ProgressBar mPbLoading;
    private TextView mTvTitle;
    private LinearLayout mPtTitleBar;

    int iconShrink = R.drawable.shrink;
    int iconExpand = R.drawable.expand;

    private static final int TIME_AUTO_HIDE_BARS_DELAY = 3800;

    private long mCurrentDownTime = 0;//当前action_down时的时间值
    private long mLastDownTime = 0;//上次action_down的时间值，防止快速触摸多次触发
    private static final int MIN_CLICK_INTERVAL = 400;//连续两次down事件最小时间间隔(ms)
    private int mCurOrientation;
    private ImageView mIvToggleExpandable;

    /**
     * 判断连续两次触摸事件间隔是否符合要求,避免快速点击等问题
     *
     * @return
     */
    private boolean isTouchEventValid() {
        if (mCurrentDownTime - mLastDownTime >= MIN_CLICK_INTERVAL) {
            return true;
        }
        return false;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        setOrientation(OrientationUtil.getOrientation(this));
    }

    /**
     * 屏幕方向改变时,回调该方法
     *
     * @param orientation 新屏幕方向:<br>
     */
    public void setOrientation(int orientation) {
        mCurOrientation = orientation;
        //更新全屏图标
        if (orientation == OrientationUtil.HORIZONTAL) {
            mIvToggleExpandable.setImageResource(iconShrink);
        } else {
            mIvToggleExpandable.setImageResource(iconExpand);
        }
        sendAutoHideBarsMsg();
    }

    /**
     * 网络是否可用
     *
     * @return true-有网络
     */
    public static boolean isNetworkAvailable(@NonNull Context cxt) {
        ConnectivityManager manager = (ConnectivityManager)cxt.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        boolean connected = false;
        if (networkInfo != null && networkInfo.isConnected()) {
            connected = true;
        }
        return connected;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏标题
        getWindow().setFlags(LayoutParams.FLAG_FULLSCREEN,
            LayoutParams.FLAG_FULLSCREEN);//设置全屏
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.pdf_view_activity);
        initView();

        Intent intent = getIntent();
        mPdfUrl = intent.getStringExtra("url");
        mPdfTitle = intent.getStringExtra("title");
        if (TextUtils.isEmpty(mPdfUrl)) {
            onLoadFail("打开pdf文件失败！");
            return;
        }

        if (TextUtils.isEmpty(mPdfTitle)) {
            mPdfTitle = "PDF";
        }
        mTvTitle.setText(mPdfTitle);

        if (!isNetworkAvailable(this)) {
            onLoadFail("没有网络");
            return;
        }
        mPbLoading.setVisibility(VISIBLE);
        String fineName = mPdfUrl;
        int index = mPdfUrl.lastIndexOf("/");
        if (index != -1) {
            fineName = mPdfUrl.substring(index);
        }
        Uri uri = Uri.parse(mPdfUrl);
        displayFromFile1(mPdfUrl, fineName);
    }

    /**
     * 获取打开网络的pdf文件
     *
     * @param fileUrl
     * @param fileName
     */
    private void displayFromFile1(String fileUrl, String fileName) {
        mPdfView.fileFromLocalStorage(this, this, this, fileUrl, fileName);   //设置pdf文件地址

    }

    /**
     * 翻页回调
     *
     * @param page
     * @param pageCount
     */
    @Override
    public void onPageChanged(int page, int pageCount) {
        //Toast.makeText(PdfActivity.this, "page= " + page +
        //    " pageCount= " + pageCount, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //强制弹出标题栏和控制栏
        forceShowOrHideBars(true);
        sendAutoHideBarsMsg();
    }

    /**
     * 加载完成回调
     *
     * @param nbPages 总共的页数
     */
    @Override
    public void loadComplete(int nbPages) {
        Toast.makeText(PdfActivity.this, "PDF加载完成" + nbPages, Toast.LENGTH_SHORT).show();
        mPbLoading.setVisibility(GONE);
        mOpenFail.setVisibility(GONE);
        sendAutoHideBarsMsg();
    }

    @Override
    public void onProgress(int progress) {

    }

    @Override
    public void onLoadFail(String message) {
        mPbLoading.setVisibility(GONE);
        mOpenFail.setVisibility(VISIBLE);
        mOpenFail.setText(message);
    }

    @Override
    public void onLayerDrawn(Canvas canvas, float pageWidth, float pageHeight, int displayedPage) {
        // Toast.makeText( MainActivity.this ,  "pageWidth= " + pageWidth + "
        // pageHeight= " + pageHeight + " displayedPage="  + displayedPage , Toast.LENGTH_SHORT).show();
    }

    //@Override
    //public boolean onTouchEvent(MotionEvent event) {
    //    return mGestureDetector.onTouchEvent(event);
    //}

    //@Override
    //public boolean dispatchTouchEvent(MotionEvent ev) {
    //    return mGestureDetector.onTouchEvent(ev);
    //}

    private void initView() {
        mPdfView = (PDFView)findViewById(R.id.pdfView);
        mOpenFail = (TextView)findViewById(R.id.openFail);
        mPbLoading = (ProgressBar)findViewById(R.id.pb_loading);
        mTvTitle = (TextView)findViewById(R.id.tv_title);
        mPtTitleBar = (LinearLayout)findViewById(R.id.pt_title_bar);
        mIvToggleExpandable = (ImageView)findViewById(R.id.iv_toggle_expandable);
        findViewById(R.id.rl_toggle_expandable).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                OrientationUtil.changeOrientation(PdfActivity.this);
            }
        });
        mPdfView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mCurrentDownTime = Calendar.getInstance().getTimeInMillis();
                if (isTouchEventValid()) {
                    mHandler.removeMessages(MSG_AUTO_HIDE_BARS);
                    animateShowOrHideBars(mPtTitleBar.getVisibility() != View.VISIBLE);
                    mLastDownTime = mCurrentDownTime;
                }
            }
        });
        findViewById(R.id.rl_back).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initAnimation();
    }

    /**
     * 初始化标题栏/控制栏显隐动画效果
     */
    private void initAnimation() {
        mEnterFromTop = AnimationUtils.loadAnimation(this, R.anim.enter_from_top);
        mExitFromTop = AnimationUtils.loadAnimation(this, R.anim.exit_from_top);

        mEnterFromTop.setAnimationListener(new AnimationImpl() {
            @Override
            public void onAnimationEnd(Animation animation) {
                super.onAnimationEnd(animation);
                mPtTitleBar.setVisibility(VISIBLE);
            }
        });
        mExitFromTop.setAnimationListener(new AnimationImpl() {
            @Override
            public void onAnimationEnd(Animation animation) {
                super.onAnimationEnd(animation);
                mPtTitleBar.setVisibility(GONE);
            }
        });
    }

    private Animation mEnterFromTop;
    private Animation mExitFromTop;
    private static final int MSG_AUTO_HIDE_BARS = 2;//隐藏标题栏和控制条

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int what = msg.what;
            if (what == MSG_AUTO_HIDE_BARS) {
                animateShowOrHideBars(false);
            }
        }
    };

    /**
     * 发送message给handler,自动隐藏标题栏
     */
    private void sendAutoHideBarsMsg() {
        //  初始自动隐藏标题栏和控制栏
        mHandler.removeMessages(MSG_AUTO_HIDE_BARS);
        mHandler.sendEmptyMessageDelayed(MSG_AUTO_HIDE_BARS, TIME_AUTO_HIDE_BARS_DELAY);
    }

    /**
     * 直接显隐标题栏和控制栏
     */
    private void forceShowOrHideBars(boolean show) {
        mPtTitleBar.clearAnimation();

        if (show) {
            mPtTitleBar.setVisibility(VISIBLE);
        } else {
            mPtTitleBar.setVisibility(GONE);
        }
    }

    /**
     * 带动画效果的显隐标题栏和控制栏
     */
    private void animateShowOrHideBars(boolean show) {
        mPtTitleBar.clearAnimation();

        if (show) {
            if (mPtTitleBar.getVisibility() != VISIBLE) {
                mPtTitleBar.startAnimation(mEnterFromTop);
            }
        } else {
            if (mPtTitleBar.getVisibility() != GONE) {
                mPtTitleBar.startAnimation(mExitFromTop);
            }
        }
    }

}
